package com.stylefeng.guns.rest.modular.wz.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.rest.common.constant.WzConsts;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.StringUtils;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.EnWz;
import com.stylefeng.guns.rest.enums.EnWzUser;
import com.stylefeng.guns.rest.enums.EnWzUserFinanceRecord;
import com.stylefeng.guns.rest.enums.EnWzUserSms;
import com.stylefeng.guns.rest.modular.wz.controller.AsyncService;
import com.stylefeng.guns.rest.modular.wz.service.IWzUserInfoService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.rest.modular.wz.util.AliPushUtil;
import com.stylefeng.guns.rest.modular.wz.util.wz.IDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户活动信息表 服务实现类
 * </p>
 *
 * @author ruiyifeng123
 * @since 2018-03-26
 */
@Service
public class WzUserInfoServiceImpl extends ServiceImpl<WzUserInfoMapper, WzUserInfo> implements IWzUserInfoService {

    @Autowired
    private  WzUserMapper wzUserMapper;
    @Autowired
    private WzUserFixedInfoMapper wzUserFixedInfoMapper;
    @Autowired
    private WzUserSmsMapper wzUserSmsMapper;
    @Autowired
    private WzUserOauthMapper wzUserOauthMapper;
    @Autowired
    private WzConsts wzConsts;
    @Autowired
    private WzUserFinanceRecordMapper wzUserFinanceRecordMapper;
    @Autowired
    private WzUserRecommendMapper wzUserRecommendMapper;
    @Autowired
    private WzUserFixedInfoMapper userFixedInfoMapper;
    @Autowired
    private WzUserMessageMapper userMessageMapper;
    @Autowired
    private AsyncService asyncService;

    /**
     * 新增用户，用户没有三方注册 userCode
     */
    @Transactional
    public boolean addUser(WzUser wzUser, ParamMap params, Map map, List<WzUserSms> wzUserSmsList,String invitationCode){
        wzUser.setAccount(params.getStr("account"));
        wzUser.setPassword(params.getStr("password"));
        wzUser.setLoginInfo(params.getStr("loginInfo"));
        wzUser.setUpdateTime(new Date());
        //新建用户固定信息
        WzUserFixedInfo wzUserFixedInfo = new WzUserFixedInfo();
        wzUserFixedInfo.setUserCode(wzUser.getUserCode());
        wzUserFixedInfo.setRegisterTime(new Date());
        int r = wzUserMapper.insert(wzUser);
        if(r > 0){
            int rr = wzUserFixedInfoMapper.insert(wzUserFixedInfo);
            if(rr > 0){
                for(WzUserSms s :wzUserSmsList){
                    s.setStatus(EnWzUserSms.STATUS_UNAVAILABLE.getIndex());
                    wzUserSmsMapper.updateById(s);
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 更新用户,用户已经三方注册
     */
    @Transactional
    public boolean updateUser(WzUser wzUser,List<WzUserSms> wzUserSmsList,ParamMap params){
        wzUser.setLoginInfo(params.getStr("loginInfo"));
        wzUser.setPassword(params.getStr("password"));
        wzUser.setUpdateTime(new Date());
        int r = wzUserMapper.updateById(wzUser);
        if(r > 0){
            for(WzUserSms s :wzUserSmsList){
                s.setStatus(EnWzUserSms.STATUS_UNAVAILABLE.getIndex());
                wzUserSmsMapper.updateById(s);
                return true;
            }
        }
        return false;
    }


    /**
     * 忘记密码
     */
    @Transactional
    public boolean forgetPswCheck(WzUser WzUser,List<WzUserSms> wzUserSmsList){
        int r = wzUserMapper.updateById(WzUser);
        if(r > 0){
            for(WzUserSms s :wzUserSmsList){
                s.setStatus(EnWzUserSms.STATUS_UNAVAILABLE.getIndex());
                wzUserSmsMapper.updateById(s);
            }
            return true;
        }
        return false;
    }

    /**
     * 三方登录用户第一次登录
     */
    @Transactional
    public boolean oauthSaveUser( WzUser wzUser,ParamMap params, List<WzUserSms> wzUserSmsList){
        //用户数据保存
        wzUser.setAccount(params.getStr("account"));
        wzUser.setLoginInfo(params.getStr("loginInfo"));
        wzUser.setUpdateTime(new Date());
        wzUser.setNickName(params.getStr("nickName"));
        wzUser.setGender(Integer.parseInt(params.getStr("gender")));
        wzUser.setAvatarUrl(params.getStr("avatarUrl"));
        wzUser.setCreateTime(new Date());
        //用户邀请码
        String invitationCode  = wzUser.getAccount().substring(8,11)+wzUser.getUserCode().toString().substring(15,18);
        List<WzUser> userFixedInfos = wzUserMapper.selectList(new EntityWrapper<WzUser>().eq("invitation_code",invitationCode));
        if(userFixedInfos.size() > 0){
            invitationCode = invitationCode + IDUtil.random(1);
            List<WzUser> userFixedInfos1 = wzUserMapper.selectList(new EntityWrapper<WzUser>().eq("invitation_code",invitationCode));
            if(userFixedInfos1.size() > 0){
                invitationCode = invitationCode + IDUtil.random(1);
            }
        }
        wzUser.setInvitationCode(invitationCode);

        //新建三方用户
        WzUserOauth wzUserOauth = new WzUserOauth();
        wzUserOauth.setCreateTime(new Date());
        wzUserOauth.setNickName(params.getStr("nickName"));
        wzUserOauth.setAvatarUrl(params.getStr("avatarUrl"));
        wzUserOauth.setGender(Integer.parseInt(params.getStr("gender")));
        wzUserOauth.setUserCode(wzUser.getUserCode());
        wzUserOauth.setOpenid(params.getStr("openid"));
        wzUserOauth.setUnionid(params.getStr("unionid"));

        //新建用户固定信息
        WzUserFixedInfo wzUserFixedInfo = new WzUserFixedInfo();
        wzUserFixedInfo.setUserCode(wzUser.getUserCode());
        wzUserFixedInfo.setRegisterTime(new Date());
        wzUserFixedInfo.setWeixinOpenid(params.getStr("openid"));
        wzUserFixedInfo.setUnionid(params.getStr("unionid"));
        int r = wzUserMapper.insert(wzUser);//新建用户
        if(r > 0){
            r = wzUserFixedInfoMapper.insert(wzUserFixedInfo);//新建用户固定信息
            if(r > 0){
                r = wzUserOauthMapper.insert(wzUserOauth);//新建用户三方登陆
                if(r > 0){
                    for(WzUserSms s :wzUserSmsList){
                        s.setStatus(EnWzUserSms.STATUS_UNAVAILABLE.getIndex());
                        wzUserSmsMapper.updateById(s);
                    }
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 三方登录用户已注册
     */
    @Transactional
    public boolean oauthUpdateUser(WzUser wzUser,ParamMap params, List<WzUserSms> wzUserSmsList){
        wzUser.setLoginInfo(params.getStr("loginInfo"));
        wzUser.setUpdateTime(new Date());

        List<WzUserFixedInfo> userFixedInfos = userFixedInfoMapper.selectList(new EntityWrapper<WzUserFixedInfo>().eq("user_code",wzUser.getUserCode()));
        userFixedInfos.get(0).setWeixinOpenid(params.getStr("openid"));
        userFixedInfoMapper.updateAllColumnById(userFixedInfos.get(0));

        //新建三方用户
        WzUserOauth wzUserOauth = new WzUserOauth();
        wzUserOauth.setCreateTime(new Date());
        wzUserOauth.setNickName(params.getStr("nickName"));
        wzUserOauth.setAvatarUrl(params.getStr("avatarUrl"));
        wzUserOauth.setGender(Integer.parseInt(params.getStr("gender")));
        wzUserOauth.setUserCode(wzUser.getUserCode());
        wzUserOauth.setOpenid(params.getStr("openid"));
        wzUserOauth.setUnionid(params.getStr("unionid"));
        int r = wzUserMapper.updateById(wzUser);
        if(r > 0){
            r = wzUserOauthMapper.insert(wzUserOauth);//新建用户三方登陆
            if(r > 0){
                for(WzUserSms s :wzUserSmsList){
                    s.setStatus(EnWzUserSms.STATUS_UNAVAILABLE.getIndex());
                    wzUserSmsMapper.updateById(s);
                }
                return true;
            }
        }
        return false;
    }

    /**
     * 用户输入邀请码
     */
    @Transactional
    public boolean saveUserRecommend(WzUser invitationUser, Long userCode) throws Exception{
        List<WzUser> users = wzUserMapper.selectList(new EntityWrapper<WzUser>().eq("user_code",userCode));//输入邀请码的人
        //新建用户邀请关系
        WzUserRecommend userRecommend = new WzUserRecommend();
        userRecommend.setAcceptUserCode(invitationUser.getUserCode());
        userRecommend.setApplicantUserCode(userCode);
        userRecommend.setCreateTime(new Date());
        userRecommend.setNickName(users.get(0).getNickName());
        userRecommend.setAvatarUrl(users.get(0).getAvatarUrl());
        userRecommend.setInvitationReward(wzConsts.getInvitationReward()*100);
        //新建用户资金记录
        WzUserFinanceRecord userFinanceRecord = new WzUserFinanceRecord();
        userFinanceRecord.setAmount(wzConsts.getInvitationReward()*100);
        userFinanceRecord.setCreateTime(new Date());
        userFinanceRecord.setPayTime(new Date());
        userFinanceRecord.setPayMethod(EnWzUserFinanceRecord.payMethod_wz.getIndex());
        userFinanceRecord.setType(EnWzUserFinanceRecord.TYPE_IN.getIndex());
        userFinanceRecord.setStatus(EnWzUserFinanceRecord.STATUS_SUCCESS.getIndex());
        userFinanceRecord.setTitle(EnWzUserFinanceRecord.TITLE_userRecommend.getName());
        userFinanceRecord.setRemark("申请人用户编号:"+userCode);
        userFinanceRecord.setUserCode(invitationUser.getUserCode());
        userFinanceRecord.setPayType(EnWzUserFinanceRecord.TITLE_userRecommend.getIndex());
        //用户消息
        WzUserMessage userMessage = new WzUserMessage();//用户消息
        userMessage.setCreateTime(new Date());
        userMessage.setType(EnWzUser.Message_Type_Index_User_Center.getIndex());
        userMessage.setUserCode(invitationUser.getUserCode());
        userMessage.setContent("尊敬的用户您好,"+users.get(0).getNickName()+"通过您的邀请码注册成功,您获得"+wzConsts.getInvitationReward()+"元收益，请注意查看!");
        userMessage.setTitle("邀请码收益到账成功");
        invitationUser.setIsRead(0);
        boolean f = saveData(userRecommend,userFinanceRecord,userMessage,invitationUser);
        if(f){
            //发送通知
            if(invitationUser.getMobileType() == 1){//ios
                asyncService.invitationNotice(1,invitationUser.getUserCode().toString(),userMessage.getTitle(),userMessage.getContent(),userMessage.getType());
//                AliPushUtil.pushNoticeToIOSAccount(invitationUser.getUserCode().toString(),userMessage.getTitle(),userMessage.getContent(),userMessage.getType(),null);
            }else if(invitationUser.getMobileType() == 2){//安卓
                asyncService.invitationNotice(2,invitationUser.getUserCode().toString(),userMessage.getTitle(),userMessage.getContent(),userMessage.getType());
//                AliPushUtil.pushNoticeToAndroidAccount(invitationUser.getUserCode().toString(),userMessage.getTitle(),userMessage.getContent(),userMessage.getType(),null);
            }
            return true;
        }else{
            return false;
        }
    }

    @Transactional
    private boolean saveData(WzUserRecommend userRecommend,WzUserFinanceRecord userFinanceRecord,WzUserMessage userMessage,WzUser user){
        int r = wzUserFinanceRecordMapper.insert(userFinanceRecord);
        if(r > 0){
            r = wzUserRecommendMapper.insert(userRecommend);
            if(r > 0){
                r = userMessageMapper.insert(userMessage);;
                if(r > 0){
                    r = wzUserMapper.updateById(user);
                    if(r > 0){
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 绑定支付宝账号
     */
    @Transactional
    public boolean saveAlipayOauth(Long userCode, ParamMap paramMap) {
        List<WzUser> userList = wzUserMapper.selectList(new EntityWrapper<WzUser>().eq("user_code",userCode));
        boolean a = false;
        if(StringUtils.isBlankStr(userList.get(0).getNickName())){
            userList.get(0).setNickName((String) paramMap.get("nickName"));
            a = true;
        }
        if(StringUtils.isBlankStr(userList.get(0).getAvatarUrl())){
            userList.get(0).setAvatarUrl((String) paramMap.get("avatarUrl"));
            a = true;
        }
        if(userList.get(0).getGender() == 0){
            userList.get(0).setGender(paramMap.getInt("gender"));
            a = true;
        }
        if(a){
            wzUserMapper.updateById(userList.get(0));
        }
        List<WzUserFixedInfo> userFixedInfos = wzUserFixedInfoMapper.selectList(new EntityWrapper<WzUserFixedInfo>().eq("user_code",userCode));
        if(!StringUtils.isBlankStr(userFixedInfos.get(0).getAlipayUserId())){
            return false;
        }else{
            userFixedInfos.get(0).setAlipayUserId(paramMap.getStr("userId"));
            wzUserFixedInfoMapper.updateById(userFixedInfos.get(0));
        }

        //新建三方用户
        WzUserOauth wzUserOauth = new WzUserOauth();
        wzUserOauth.setCreateTime(new Date());
        wzUserOauth.setNickName(paramMap.getStr("nickName"));
        wzUserOauth.setAvatarUrl(paramMap.getStr("avatarUrl"));
        wzUserOauth.setGender(Integer.parseInt(paramMap.getStr("gender")));
        wzUserOauth.setUserCode(userCode);
        wzUserOauth.setAlipayUserId(paramMap.getStr("userId"));
        wzUserOauth.setPaltform(EnWzUser.OAUTH_PALTFORM_alipay.getIndex());
        int r = wzUserOauthMapper.insert(wzUserOauth);
        if(r > 0){
            return true;
        }
        return false;
    }

    /**
     * 修改密码
     */
    @Transactional
    public Res updatePsw(ParamMap p, Long userCode) {
        List<WzUser> userList = wzUserMapper.selectList(new EntityWrapper<WzUser>().eq("user_code",userCode));
        //查询验证码
        EntityWrapper<WzUserSms> ew = new EntityWrapper<>();
        ew.eq("tel",userList.get(0).getAccount()).eq("type",EnWzUserSms.TYPE_VERIFICATION_UPDATE_PSW.getIndex()).eq("vaild_code",p.getStr("vaildCode")).eq("status",EnWzUserSms.STATUS_AVAILABLE.getIndex());
        List<WzUserSms> wzUserSmsList = wzUserSmsMapper.selectList(ew);
        if(wzUserSmsList.size() > 0) {
            for (WzUserSms s : wzUserSmsList) {
                if (!new Date().before(s.getEndTime())) {
                    return Res.fail("验证码已失效!");
                }
            }
            //修改密码并更新
            userList.get(0).setPassword(p.getStr("password"));
            int r = wzUserMapper.updateById(userList.get(0));
            if(r > 0){
                for(WzUserSms s :wzUserSmsList){
                    s.setStatus(EnWzUserSms.STATUS_UNAVAILABLE.getIndex());
                    wzUserSmsMapper.updateById(s);
                }
            }else{
                return Res.fail();
            }
        }else{
            return Res.fail("验证码错误!");
        }
        return Res.success();
    }

    /**
     * 绑定新手机号
     */
    public Res bindAccount(ParamMap p, Long userCode) {
        List<WzUser> userList = wzUserMapper.selectList(new EntityWrapper<WzUser>().eq("user_code",userCode));
        if(p.getInt("type") == 1){
            //查询验证码
            EntityWrapper<WzUserSms> ew = new EntityWrapper<>();
            ew.eq("tel",p.getStr("oldAccount")).eq("type",EnWzUserSms.TYPE_VERIFICATION_BIND_OLDACCOUNT.getIndex()).eq("vaild_code",p.getStr("vaildCode")).eq("status",EnWzUserSms.STATUS_AVAILABLE.getIndex());
            List<WzUserSms> wzUserSmsList = wzUserSmsMapper.selectList(ew);
            if(wzUserSmsList.size() > 0) {
                for (WzUserSms s : wzUserSmsList) {
                    if (!new Date().before(s.getEndTime())) {
                        return Res.fail("验证码已失效!");
                    }
                }
                for(WzUserSms s :wzUserSmsList){
                    s.setStatus(EnWzUserSms.STATUS_UNAVAILABLE.getIndex());
                    wzUserSmsMapper.updateById(s);
                }
                return Res.success();
            }else{
                return Res.fail("验证码错误!");
            }
        }else if(p.getInt("type") == 2){
            //查询验证码
            EntityWrapper<WzUserSms> ew = new EntityWrapper<>();
            ew.eq("tel",p.getStr("newAccount")).eq("type",EnWzUserSms.TYPE_VERIFICATION_BIND_NEWACCOUNT.getIndex()).eq("vaild_code",p.getStr("vaildCode")).eq("status",EnWzUserSms.STATUS_AVAILABLE.getIndex());
            List<WzUserSms> wzUserSmsList = wzUserSmsMapper.selectList(ew);
            if(wzUserSmsList.size() > 0) {
                for (WzUserSms s : wzUserSmsList) {
                    if (!new Date().before(s.getEndTime())) {
                        return Res.fail("验证码已失效!");
                    }
                }
                //修改账号并更新
                userList.get(0).setAccount(p.getStr("newAccount"));
                int r = wzUserMapper.updateById(userList.get(0));
                if(r > 0){
                    for(WzUserSms s :wzUserSmsList){
                        s.setStatus(EnWzUserSms.STATUS_UNAVAILABLE.getIndex());
                        wzUserSmsMapper.updateById(s);
                    }
                }
            }else{
                return Res.fail("验证码错误!");
            }
            return Res.success();
        }
        return Res.fail();
    }
}
